import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import { RouteRecordRaw } from "vue-router";
import { constantRoutes, asyncRoutes } from "../router";
/**
 * Use meta.role to determine if the current user has permission
 */
function hasPermission(menus: number[], route: RouteRecordRaw) {
    if (route.meta && route.meta.permissionKey) {
        return menus?.includes(route.meta.permissionKey as number);
    } else {
        return true;
    }
}

/**
 * 过滤有权限访问的页面路由
 * @returns RouteRecordRaw[]
 */
export function filterAsyncRoutes(routes: RouteRecordRaw[], menus: number[]): RouteRecordRaw[] {
    const res: RouteRecordRaw[] = [];
    routes.forEach((route) => {
        const tmp = { ...route };
        if (hasPermission(menus, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, menus);
            }
            res.push(tmp);
        }
    });
    return res;
}

export const usePermissionStore = defineStore("permisson", () => {
    const accessedRoutes = reactive<RouteRecordRaw[]>(constantRoutes);

    function generateRoutes(menus: number[]) {
        const result = filterAsyncRoutes(asyncRoutes, menus);
        if (result.length > 0) {
            // 处理首页
            result.push({
                path: "/",
                redirect: result[0].path,
                meta: { title: "", hidden: true },
            });
        } else {
            result.push({
                path: "/",
                redirect: "/403",
                meta: { title: "", hidden: true },
            });
        }
        accessedRoutes.push(...result);
        return result;
    }

    return { accessedRoutes, generateRoutes };
});
